import time
import random
import hmac
import hashlib
import binascii
import base64
import json


# from https://cloud.tencent.com/developer/article/1451250

class Auth:
    def __init__(self, action, secretId, s, r='ap-guangzhou'):
        self.Action, self.SecretId, self.Secretkey, self.Region = action, secretId, s, r
        self.Timestamp, self.Nonce = int(time.time()), random.randint(0, 999999999)
        print(self.Timestamp)
        print(self.Nonce)

    def make(self, requestHost, requestUri, params, method='POST'):
        params['Action'] = self.Action
        params['SecretId'] = self.SecretId
        params['Timestamp'] = self.Timestamp
        params['Nonce'] = self.Nonce
        # params['Region'] = self.Region
        ps = '&'.join('%s=%s' % (i, params[i]) for i in sorted(params))
        source_str = '%s%s%s?%s' % (method.upper(), requestHost, requestUri, ps)
        print(source_str + "&Signature=")
        source_str = bytes(source_str, encoding='utf-8')
        secretkey = bytes(self.Secretkey, encoding='utf-8')
        hexstring = hmac.new(secretkey, source_str, hashlib.sha1)
        base64s = binascii.b2a_base64(hexstring.digest())[:-1]
        return base64s.decode()


if __name__ == '__main__':
    a = Auth('GetCdnMiddleSourceList', 'AKxxx', 'MSxxx', 'ap-guangzhou')
    sign = a.make('cdn.api.qcloud.com', '/v2/index.php', {})
    print(sign)
